﻿using System;
using BingoClientModel;
using HPSocketCS;
using BingoServerCommon.Common;

namespace _TestClient
{
	public partial class Client
    {
		private readonly TcpPackClient _client = new TcpPackClient();


	    private readonly TcpPackClient _gameServerclient = new TcpPackClient();

		public Client()
		{
			InitializeComponent();
		}

	    #region 构造单例模式,防止出现多个同样窗口

	    public static Client instance;

	    public static Client CreateForm()
	    {
	        if (instance == null || instance.IsDisposed)
	        {
	            instance = new Client();
	        }
	        return instance;
	    }

	    #endregion


        /// <summary>
        /// 执行连接
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void buttonStart_Click(object sender, EventArgs e)
		{
		    try
		    {
		        String ip = "192.168.0.121";
		        ushort port = 10000;

		        if (_client.Connect(ip, port, checkBoxAsyncConn.Checked))
		        {
		            if (checkBoxAsyncConn.Checked == false)
		            {
		                // SetAppState(AppState.Started);
		            }

		            //AddMsg(string.Format("$Client Start OK -> ({0}:{1})", ip, port));
		        }
		        else
		        {
		            //SetAppState(AppState.Stoped);
		            throw new Exception($"$Client Start Error -> {_client.ErrorMessage}({_client.ErrorCode})");
		        }
		    }
		    catch (Exception ex)
		    {
		        //AddMsg(ex.Message);
		    }
		    finally
		    {
		        connect_toolStripStatusLabel.Text = _client.State.ToString();
		    }
        }

        private void buttonStop_Click(object sender, EventArgs e)
        {
            // 停止服务
           // AddMsg("$Server Stop");
            if (_client.Stop())
            {
                //SetAppState(AppState.Stoped);
            }
            else
            {
                //AddMsg(string.Format("$Stop Error -> {0}({1})", client.ErrorMessage, client.ErrorCode));
            }

            connect_toolStripStatusLabel.Text = _client.State.ToString();
        }

        private void buttonSend_Click(object sender, EventArgs e)
        {
            try
            {
                string send = textBoxSendMsg.Text;
                if (send.Length == 0)
                {
                    return;
                }

                Package pack = new Package(EnumPackCommand.CS_Login);
                pack.Write(5);
                for (int i = 0; i < 5; i++)
                {
                    pack.Write(i);
                    pack.Write("name");
                }
                pack.Write(10);
                pack.Write("sdgfsdgdsfhg");

                byte[] bytes = pack.GetBuffer();

                
                IntPtr connId = _client.ConnectionId;

                // 发送
                if (_client.Send(bytes, bytes.Length))
                {
                    //AddMsg(string.Format("$ ({0}) Send OK --> {1}", connId, send));
                }
                else
                {
                    //AddMsg(string.Format("$ ({0}) Send Fail --> {1} ({2})", connId, send, bytes.Length));
                }

            }
            catch (Exception ex)
            {
                //AddMsg(string.Format("$ Send Fail -->  msg ({0})", ex.Message));
            }
        }

	    private delegate void ShowMsg(string msg);
        private ShowMsg AddMsgDelegate;
        private void Client_Load(object sender, EventArgs e)
        {
            try
            {
                // 加个委托显示msg,因为on系列都是在工作线程中调用的,ui不允许直接操作
                AddMsgDelegate = AddMsg;

				// 设置client事件
				_client.OnPrepareConnect += new TcpClientEvent.OnPrepareConnectEventHandler(OnPrepareConnect);
				_client.OnConnect += new TcpClientEvent.OnConnectEventHandler(OnConnect);
				_client.OnSend += new TcpClientEvent.OnSendEventHandler(OnSend);
				_client.OnReceive += new TcpClientEvent.OnReceiveEventHandler(OnReceive);
				_client.OnClose += new TcpClientEvent.OnCloseEventHandler(OnClose);


				// 设置client事件
				_gameServerclient.OnPrepareConnect += new TcpClientEvent.OnPrepareConnectEventHandler(OnPrepareConnect);
	            _gameServerclient.OnConnect += new TcpClientEvent.OnConnectEventHandler(OnConnect);
	            _gameServerclient.OnSend += new TcpClientEvent.OnSendEventHandler(OnSend);
	            _gameServerclient.OnReceive += new TcpClientEvent.OnReceiveEventHandler(OnReceive);
	            _gameServerclient.OnClose += new TcpClientEvent.OnCloseEventHandler(OnClose);


				// 设置包头标识,与对端设置保证一致性
				_client.PackHeaderFlag = 0xa3;
				// 设置最大封包大小
				_client.MaxPackSize = 0x256;



				// 设置包头标识,与对端设置保证一致性
				_gameServerclient.PackHeaderFlag = 0xa3;
				// 设置最大封包大小
	            _gameServerclient.MaxPackSize = 0x256;

				//SetAppState(AppState.Stoped);

				//注册
				PackageRegister.PackagesRegister();


			}
            catch (Exception ex)
            {
                //SetAppState(AppState.Error);
                AddMsg(ex.Message);
            }
        }


        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void login_button_Click(object sender, EventArgs e)
        {
            LoginForm.CreateForm().loginDeleInstance = Login;
            LoginForm.CreateForm().Show();
        }


		/// <summary>
		/// 点击，开始进入游戏，即建立一个新的连接，与GameServer
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		private void enterGame_btn_Click(object sender, EventArgs e)
		{
			try
			{
				String ip = "192.168.0.121";
				ushort port = 10001;

				if (_gameServerclient.Connect(ip, port, checkBoxAsyncConn.Checked))
				{
					if (checkBoxAsyncConn.Checked == false)
					{
						//SetAppState(AppState.Started);
					}

					AddMsg($"连接游戏服成功 Client Start OK -> ({ip}:{port})");
				}
				else
				{
					//SetAppState(AppState.Stoped);
					throw new Exception($"$Client Start Error -> {_gameServerclient.ErrorMessage}({_gameServerclient.ErrorCode})");
				}
			}
			catch (Exception ex)
			{
				AddMsg(ex.Message);
			}
			finally
			{
				connect_toolStripStatusLabel.Text = _gameServerclient.State.ToString();
			}
		}


		/// <summary>
		/// gameServer，发消息给服务端
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
		private void button1_Click(object sender, EventArgs e)
		{
			try
			{
				Package pack = new Package(EnumPackCommand.CS_SendTest);
				pack.Write(5);
				for (int i = 0; i < 5; i++)
				{
					pack.Write(i);
					pack.Write("name");
				}
				pack.Write(10);
				pack.Write("sdgfsdgdsfhg");

				byte[] bytes = pack.GetBuffer();


				IntPtr connId = _gameServerclient.ConnectionId;

				// 发送
				if (_gameServerclient.Send(bytes, bytes.Length))
				{
					AddMsg("!!!!!!!!!!!!!!!!!~~~~~~~~~~~~~~~~~~~~~");
				}
				else
				{
					AddMsg($"$ ({connId}) Send Fail --> ({bytes.Length})");
				}

			}
			catch (Exception ex)
			{
				AddMsg($"$ Send Fail -->  msg ({ex.Message})");
			}
		}
	}
}
